import { HexiaoBox } from "./style";
import { WifiOutlined, TeamOutlined } from '@ant-design/icons';
import moment from 'moment'
import 'moment/locale/zh-cn'
import { useCallback, useEffect, useRef, useState } from "react";
import successautio from '../../audioMp3/succes.mp3'
import defeatAutio from '../../audioMp3/defeat.mp3'
import axios from "axios";
interface IProps {
    dishes: {
        amount: number,
        dishes: string,
        id: number,
        price: number,
    }[]
    id: string,
    mainName: string,
    mealDate: string,
    mealType: string,
}
const Hexiao = () => {
    const baseIp = 'https://qz.mhjxie.com:8082'
    // const baseIp = 'http://192.168.3.160:8081'
    const audioRef = useRef<HTMLAudioElement>(null)//核销成功提示音
    const defeatAudioRef = useRef<HTMLAudioElement>(null)//核销失败提示音
    const [stringData, setStringData] = useState<string>("")//键盘输入的值
    const [mqstauts, setMqstauts] = useState<boolean>(false)//判断是否连接
    const [show, setShow] = useState<boolean>(true)
    const [currentTime, setCurrentTime] = useState<string>('');//时间
    const [hexiaodata, setHexiaoData] = useState<{
        sum: number;
        notVerification: number;
        verification: number;
    }>({
        sum: 0,
        verification: 0,
        notVerification: 0
    })
    const [dishesdata, setDishesdata] = useState<IProps>(
        {
            dishes: [],
            id: "",
            mainName: "",
            mealDate: "",
            mealType: ""
        }
    )
    //核销的请求，在第一次进入和每次回车之后执行
    const handleHexiao = useCallback((value: string) => {
        axios.get(baseIp + '/ls-meal-history/consumption', {
            params: {
                id: value
            }
        })
            .then(
                res => {
                    if (res.status === 200) {
                        if (res.data.code === 20000) {
                            //播放语音 核销成功
                            audioRef.current?.play()
                        } else {
                            defeatAudioRef.current?.play()
                            //播放语音 核销失败
                            handleModal(res.data.msg)
                        }
                    }
                    setShow(true);
                    handlegetHexiaoData()
                }
            )
            .catch(err => {
                setShow(true);
            })
    }, [])
    document.onkeydown = function (e) {
        if (show) {
            if (e.key === 'Enter') {
                try {
                    // 使用正则表达式进行替换
                    let decodedString: string = stringData.replace(/Shift/g, '');
                    console.log(decodedString);

                    // 尝试解码 base64 字符串
                    let deString = atob(decodedString);

                    // 需要解析的编码中含有 Unicode 字符
                    let unicodeString = decodeURIComponent(escape(deString));

                    // 设置数据和其他操作
                    setDishesdata(JSON.parse(unicodeString));
                    setStringData("");
                    setShow(false);
                    handleHexiao(JSON.parse(unicodeString).id);

                } catch (error) {
                    console.error('Error decoding string:', error);

                    // 如果解码失败，直接执行 setStringData("");
                    setStringData("");
                }
            } else {
                setStringData(stringData + e.key);
            }
        }
    };

    const handleModal = (value: string) => {
        // 创建一个新的div元素
        let messageDiv = document.createElement('div');
        // 设置消息内容和样式
        messageDiv.innerHTML = value;
        messageDiv.style.width = '40%';
        messageDiv.style.height = '20%';
        //文字居中
        messageDiv.style.display = 'flex';
        messageDiv.style.justifyContent = 'center';
        messageDiv.style.alignItems = 'center';
        messageDiv.style.position = 'fixed';
        messageDiv.style.bottom = '50%';
        messageDiv.style.left = '30%';
        messageDiv.style.background = '#333';
        messageDiv.style.color = '#fff';
        messageDiv.style.padding = '10px';
        messageDiv.style.borderRadius = '5px';
        //字体大小
        messageDiv.style.fontSize = '6vh';

        // 将消息添加到body中
        document.body.appendChild(messageDiv);

        // // 3秒后移除消息
        setTimeout(() => {
            document.body.removeChild(messageDiv);
        }, 1500);
    }

    const handlegetHexiaoData = () => {
        axios.get(baseIp + '/ls-meal-history/listOverview', {
            params: {
                condition: 0
            }
        }).then(
            res => {
                if (res.status === 200) {
                    setHexiaoData(res.data.data)
                    setMqstauts(navigator.onLine)
                }
            }
        )
    }

    useEffect(() => {
        //第一次获取数值
        handlegetHexiaoData()
        const updateTime = () => {
            setCurrentTime(moment(new Date().getTime()).format('HH:mm:ss'));
        };
        //时间定时器，一秒时间变一下
        const intervalId = setInterval(updateTime, 1000);
        //网络改变的话调取的回调函数
        function handleConnectionChange() {
            if (navigator.onLine) {
                setMqstauts(navigator.onLine)
            } else {
                // 在没有网络连接时执行的操作
                setMqstauts(false)
                handleModal('网络已断开')
            }
        }
        // 绑定网络连接状态变化的事件监听器
        window.addEventListener('online', handleConnectionChange);
        window.addEventListener('offline', handleConnectionChange);
        // 组件卸载时清除事件监听器
        return () => {
            clearInterval(intervalId)
            window.removeEventListener('online', handleConnectionChange);
            window.removeEventListener('offline', handleConnectionChange);
        };
    }, []); // 仅在组件挂载和卸载时执行
    return (
        <HexiaoBox >
                <div className="hexiao-top">
                    <div className="top-left">
                        <span className="content-box">
                            <WifiOutlined style={{ marginLeft: '1.5vh' }} />
                            <span style={{ marginRight: '1.5vh' }}>{mqstauts ? '已连接' : '未连接'}</span>
                        </span>
                        <span className="content-box">
                            <TeamOutlined style={{ marginLeft: '1.5vh' }} />
                            <span style={{ marginRight: '1.5vh' }}>{hexiaodata?.sum}人</span>
                        </span>
                        <div className="contentBlueBox">
                            <div className="content-title">已核销</div>
                            <div className="content-main">{hexiaodata?.verification}
                                <span style={{ fontSize: '2vh', marginLeft: '10%', marginBottom: '1%' }}>人</span>
                            </div>
                        </div>
                        <div className="contentBlueBox">
                            <div className="content-title">未核销</div>
                            <div className="content-main">{hexiaodata?.notVerification}
                                <span style={{ fontSize: '2vh', marginLeft: '10%' }}>人</span>
                            </div>
                        </div>
                    </div>
                    <div className="top-right">
                        <div className="content-time">
                            {currentTime}
                        </div>
                        <div className="content-date">{
                            moment(new Date().getTime()).format('YYYY年MM月DD日')
                        }&nbsp;&nbsp;&nbsp;
                            {moment().format('dddd')}</div>
                    </div>
                </div>
                {
                    !show ?<div className="jiazai-box"></div>:null
                }
                <div className="hexiao-bot">
                    <div className="bot-left">
                        <div className="hexiao" style={{ color: '#D0D5D7' }}>
                            核销内容
                        </div>
                        <ul className="content">
                            <li>
                                <div className="hexiao-title">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</div>
                                <div className="hexiao-data">{dishesdata?.mainName}</div>
                            </li>
                            <li>
                                <div className="hexiao-title">用餐日期</div>
                                <div className="hexiao-data">{dishesdata?.mealDate}</div>
                            </li>
                            <li>
                                <div className="hexiao-title">用餐时段</div>
                                <div className="hexiao-data">{dishesdata?.mealType}</div>
                            </li>
                            <li>
                                <div className="hexiao-title">消费合计</div>
                                <div className="hexiao-data">{
                                    // 此数据为dishesdata?.dishes 的所有单价*数量加起来
                                    dishesdata?.dishes.reduce(
                                        (pre: number, cur: { price: number; amount: number; }) => pre + cur.price * cur.amount, 0
                                    )
                                        .toFixed(2)
                                }</div>
                            </li>
                        </ul>
                    </div>
                    <div className="bot-right">
                        <div className="caipin" style={{ color: '#D0D5D7' }}>
                            菜品数据
                        </div>
                        <ul className="data">
                            <div className="caipin-title">
                                <div>菜品</div>
                                <div>用餐份数</div>
                                <div>菜品单价</div>
                                <div>菜品总价</div>
                            </div>
                            <ul className="caipin-data">
                                {
                                    dishesdata?.dishes.map((item: any, index: number) => {
                                        return (
                                            <li key={index}>
                                                <div>{item?.dishes}</div>
                                                <div>{item?.amount}</div>
                                                <div>{item?.price}</div>
                                                <div>{item?.amount * item?.price}</div>
                                            </li>
                                        )
                                    })
                                }
                            </ul>
                        </ul>
                    </div>
                </div>
            <audio src={successautio} ref={audioRef}></audio>
            <audio src={defeatAutio} ref={defeatAudioRef}></audio>
        </HexiaoBox>
    )
}

export default Hexiao;